package com.xiaofu.datasource.datasource;

import com.xiaofu.datasource.constant.DataSourceEmun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态数据源
 *
 * @author ruoyi
 */
@Component
@Primary
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Resource
    private DataSource datasourceOne;

    @Resource
    private DataSource datasourceTwo;

    @Override
    protected Object determineCurrentLookupKey()
    {
        return DynamicDataSourceContextHolder.getDateSoureType();
    }

    @Override
    public void afterPropertiesSet() {
        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put(DataSourceEmun.first, datasourceOne);
        dataSourceMap.put(DataSourceEmun.second, datasourceTwo);

        super.setTargetDataSources(dataSourceMap);

        super.setDefaultTargetDataSource(datasourceOne);

        super.afterPropertiesSet();
    }
}
